<template>
  <el-dialog :model-value="visible" :title="dialogTitle" width="800px" :close-on-click-modal="false"
    @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="warehouse-form">
      <div class="form-row">
        <!-- 左侧列 -->
        <div class="form-column">
          <h3 class="section-title">基础信息</h3>

          <el-form-item label="上级名称" prop="parentId">
            <el-select v-model="form.parentId" placeholder="请选择仓库" clearable filterable class="full-width">
              <el-option v-for="item in parentWarehouseOptions" :key="item.id" :label="item.warehouseName"
                :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="仓库名称" prop="warehouseName">
            <el-input v-model="form.warehouseName" placeholder="请输入仓库名称" class="full-width" />
          </el-form-item>

          <el-form-item label="存储类型" prop="storageTypeId">
            <el-select v-model="form.storageTypeId" placeholder="请选择存储类型" clearable filterable class="full-width">
              <el-option v-for="item in storageTypeOptions" :key="item.id" :label="item.typeName" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="负责人" prop="personInChargeId">
            <el-select v-model="form.personInChargeId" placeholder="请选择负责人" clearable filterable class="full-width">
              <el-option v-for="item in personOptions" :key="item.id" :label="item.personName || item.name || item.userName" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="仓库地址" prop="address">
            <el-input v-model="form.address" placeholder="请输入仓库地址" class="full-width" />
          </el-form-item>

          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" type="textarea" :rows="3" placeholder="请输入备注" class="full-width" />
          </el-form-item>
        </div>

        <!-- 右侧列 -->
        <div class="form-column">
          <el-form-item label="仓库编号" prop="warehouseNumber">
            <div class="warehouse-number-input">
              <el-input v-model="form.warehouseNumber" placeholder="请输入仓库编号" :disabled="form.isSystemNumber"
                class="full-width" />
              <el-checkbox v-model="form.isSystemNumber" class="system-number-checkbox">
                系统编号
              </el-checkbox>
            </div>
          </el-form-item>

          <el-form-item label="仓库分类" prop="categoryId">
            <el-select v-model="form.categoryId" placeholder="请选择仓库分类" clearable filterable class="full-width">
              <el-option v-for="item in categoryOptions" :key="item.id" :label="item.categoryName" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="仓库结构" prop="structureId">
            <el-select v-model="form.structureId" placeholder="请选择仓库结构" clearable filterable class="full-width">
              <el-option v-for="item in structureOptions" :key="item.id" :label="item.structureName" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="状态" prop="isEnabled">
            <el-checkbox v-model="form.isEnabled">
              {{ form.isEnabled ? '启用' : '禁用' }}
            </el-checkbox>
          </el-form-item>
        </div>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  getWarehouseList,
  getAllWarehouseCategories,
  getAllStorageTypes,
  getAllWarehouseStructures,
  getAllPersons,
  addWarehouse,
  updateWarehouse
} from '@/Https/server'

// Props
interface Props {
  visible: boolean
  warehouse?: any
  mode: 'add' | 'edit'
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'success': []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)
const parentWarehouseOptions = ref<any[]>([])
const categoryOptions = ref<any[]>([])
const storageTypeOptions = ref<any[]>([])
const structureOptions = ref<any[]>([])
const personOptions = ref<any[]>([])

// 表单数据
const form = reactive({
  id: '',
  warehouseNumber: '',
  warehouseName: '',
  parentId: null as number | null,
  categoryId: null as number | null,
  storageTypeId: null as number | null,
  structureId: null as number | null,
  personInChargeId: null as number | null,
  address: '',
  remarks: '',
  isEnabled: true,
  isSystemNumber: true
})

// 表单验证规则
const rules: FormRules = {
  warehouseName: [
    { required: true, message: '请输入仓库名称', trigger: 'blur' },
    { min: 2, max: 100, message: '仓库名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择仓库分类', trigger: 'change' }
  ],
  warehouseNumber: [
    { required: true, message: '请输入仓库编号', trigger: 'blur' },
    { min: 2, max: 50, message: '仓库编号长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return props.mode === 'add' ? '新增仓库' : '编辑仓库'
})

// 方法
const loadOptions = async () => {
  try {
    console.log('开始加载选项数据...')

    // 加载上级仓库选项
    const parentResponse: any = await getWarehouseList({ pageSize: 1000 })
    console.log('上级仓库响应:', parentResponse)
    if (parentResponse.success || parentResponse.code === 200 || parentResponse.Code === 200) {
      parentWarehouseOptions.value = parentResponse.data?.pageData || parentResponse.data?.PageData || parentResponse.data || []
    }

    // 加载仓库分类选项 - 使用不分页的API
    const categoryResponse: any = await getAllWarehouseCategories()
    console.log('仓库分类响应:', categoryResponse)
    if (categoryResponse.success || categoryResponse.code === 200 || categoryResponse.Code === 200) {
      categoryOptions.value = categoryResponse.data || []
    }

    // 加载存储类型选项 - 使用不分页的API
    const storageTypeResponse: any = await getAllStorageTypes()
    console.log('存储类型响应:', storageTypeResponse)
    if (storageTypeResponse.success || storageTypeResponse.code === 200 || storageTypeResponse.Code === 200) {
      storageTypeOptions.value = storageTypeResponse.data || []
    }

    // 加载仓库结构选项 - 使用不分页的API
    const structureResponse: any = await getAllWarehouseStructures()
    console.log('仓库结构响应:', structureResponse)
    if (structureResponse.success || structureResponse.code === 200 || structureResponse.Code === 200) {
      structureOptions.value = structureResponse.data || []
    }

    // 加载人员选项 - 使用不分页的API
    const personResponse: any = await getAllPersons()
    console.log('人员响应:', personResponse)
    if (personResponse.success || personResponse.code === 200 || personResponse.Code === 200) {
      personOptions.value = personResponse.data || []
    }

    console.log('选项数据加载完成')
  } catch (error) {
    console.error('加载选项数据失败:', error)
    ElMessage.error('加载选项数据失败，请检查网络连接')
  }
}

const generateWarehouseNumber = () => {
  if (form.isSystemNumber) {
    const timestamp = new Date().getTime()
    const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
    form.warehouseNumber = `CKBH${timestamp}${random}`
  }
}

const resetForm = () => {
  Object.assign(form, {
    id: '',
    warehouseNumber: '',
    warehouseName: '',
    parentId: null,
    categoryId: null,
    storageTypeId: null,
    structureId: null,
    personInChargeId: null,
    address: '',
    remarks: '',
    isEnabled: true,
    isSystemNumber: true
  })

  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const initForm = () => {
  if (props.warehouse) {
    console.log('初始化表单数据:', props.warehouse)
    
    // 规范化字段映射，确保所有字段都能正确赋值
    Object.assign(form, {
      id: props.warehouse.id ?? props.warehouse.Id ?? '',
      warehouseNumber: props.warehouse.warehouseNumber ?? props.warehouse.WarehouseNumber ?? '',
      warehouseName: props.warehouse.warehouseName ?? props.warehouse.WarehouseName ?? '',
      parentId: props.warehouse.parentId ?? props.warehouse.ParentId ?? null,
      categoryId: props.warehouse.categoryId ?? props.warehouse.CategoryId ?? null,
      storageTypeId: props.warehouse.storageTypeId ?? props.warehouse.StorageTypeId ?? null,
      structureId: props.warehouse.structureId ?? props.warehouse.StructureId ?? null,
      personInChargeId: props.warehouse.personInChargeId ?? props.warehouse.PersonInChargeId ?? null,
      address: props.warehouse.address ?? props.warehouse.Address ?? '',
      remarks: props.warehouse.remarks ?? props.warehouse.Remarks ?? '',
      isEnabled: props.warehouse.isEnabled ?? props.warehouse.IsEnabled ?? true,
      isSystemNumber: false // 编辑时不使用系统编号
    })
    
    console.log('表单数据初始化完成:', form)
  } else {
    resetForm()
    generateWarehouseNumber()
  }
}

const handleClose = () => {
  emit('update:visible', false)
  resetForm()
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    const response: any = props.mode === 'add'
      ? await addWarehouse(form)
      : await updateWarehouse(form)

    // 由于axios拦截器，response就是响应体
    if (response.code === 200) {
      ElMessage.success(props.mode === 'add' ? '新增成功' : '修改成功')
      emit('success')
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('提交失败，请检查表单数据')
  } finally {
    submitting.value = false
  }
}

// 监听器
watch(() => props.visible, (newVal) => {
  if (newVal) {
    initForm()
  }
})

watch(() => form.isSystemNumber, (newVal) => {
  if (newVal) {
    generateWarehouseNumber()
  }
})

// 生命周期
onMounted(() => {
  loadOptions()
})
</script>

<style scoped>
.warehouse-form {
  padding: 20px 0;
}

.form-row {
  display: flex;
  gap: 40px;
}

.form-column {
  flex: 1;
}

.section-title {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.full-width {
  width: 100%;
}

.warehouse-number-input {
  display: flex;
  align-items: center;
  gap: 12px;
}

.system-number-checkbox {
  white-space: nowrap;
}

.dialog-footer {
  text-align: center;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
}
</style>